﻿#region - Class details -
/*  
 *  Developer   : Wicus Botha
 *  Description : 
 *  History     : WB - 2007-12-05 - Created
 */
#endregion

using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using IQ.Base;
using IQ.Base.Services;
using IQ.BaseWindows;
using IQ.DbBase;
using IQ.WinForms;
using SqlServerAdmin;

namespace IQ.DbA
{
    partial class FrmMain : Form
    {
        #region # Constructor #
        public FrmMain()
        {
            InitializeComponent();
            Logging.ConfigureLog();
            General.DefaultGridHeaderRowHeight = 25;
            General.DefaultGridRowHeight = 23;
            loadUserSettings();
            pnlForm.BackColor = FormSettings.FormBackColor;
            connectDb.ConnectionType = ConnectionTypes.SqlServer;
            connectDb.ApplicationName = "IQ.DbA";
        }
        #endregion

        #region - Private variables -
        private ConnectionProperties connectDb = new ConnectionProperties();
        private Form CurrentForm;
        #endregion

        #region - Private methods -
        private void loadUserSettings()
        {
            FormSettings.SetThemeGreen();
            string userSet = Settings.ReadSettingString("UserDefaults", "");
            if (!String.IsNullOrEmpty(userSet))
            {
                string[] settings = userSet.Split(';');
                if (settings.Length == 10)
                {
                    FormSettings.SetColors(
                                        Color.FromArgb(settings[0].ToIntDefault(0)),
                                        Color.FromArgb(settings[1].ToIntDefault(0)),
                                        Color.FromArgb(settings[2].ToIntDefault(0)),
                                        Color.FromArgb(settings[3].ToIntDefault(0)),
                                        Color.FromArgb(settings[4].ToIntDefault(0)),
                                        Color.FromArgb(settings[5].ToIntDefault(0)),
                                        Color.FromArgb(settings[6].ToIntDefault(0)),
                                        Color.FromArgb(settings[7].ToIntDefault(0)),
                                        Color.FromArgb(settings[8].ToIntDefault(0)),
                                        Color.FromArgb(settings[9].ToIntDefault(0)));
                }
            }
        }
        private string get_A_ConnectionString(string dbName)
        {
            connectDb.Database = dbName;
            connectDb.TestConnectionString();
            return connectDb.GetConnectionString();
        }
        private string getMaintenanceConnectString()
        {
            btnConnectD.Image = IQ.DbA.Properties.Resources.RedDot;
            string newConnect = get_A_ConnectionString("master");
            DbHelper.SetConnectionString(newConnect);
            SqlMaintenance.Kill_AppConnections(connectDb.ApplicationName);
            return newConnect;
        }
        private void setUserAndPassword()
        {
            frmSetupConnection frmCon = new frmSetupConnection();
            frmCon.LockConnectionType(ConnectionTypes.SqlServer);
            frmCon.Connection = connectDb;
            frmCon.ShowDialog();
        }
        private bool connectToServer(string serverName, bool getUserID)
        {
            //ConnectionProperties connect = new ConnectionProperties();
            connectDb.Name = serverName;
            if (ServerConnections.Instance.ServerList.ContainsKey(serverName) && !getUserID)
                connectDb.SetConnectionString(ServerConnections.Instance.GetServerConnectString(connectDb.Name));
            else
            {
                // Get new connection
                this.setUserAndPassword();
            }
            string conResult = connectDb.TestConnectionString();
            if (connectDb.CanConnect)
            {
                ServerConnections.Instance.SetServerConnectionStr(connectDb.Name, connectDb.GetConnectionString());
                DbHelper.SetConnectionString(connectDb.GetConnectionString());
                return true;
            }
            else
            {
                // conResult
                if (General.MesDlg("Could not connect to server, try with different user & password?", 'C') == DialogResult.Yes)
                    return connectToServer(serverName, true);
                else
                    return false;
            }
        }
        private void closeCurrentForm()
        {
            if (CurrentForm != null)
            {
                CurrentForm.Close();
                CurrentForm.Dispose();
            }
        }
        private void load_A_Form(int FormTag)
        {
            if (FormTag > 1000)
            {
                closeCurrentForm();
                if (DbHelper.CanConnect)
                {
                    switch (FormTag)
                    {
                        case 1001: CurrentForm = new FrmTables(); break;
                        case 1002: CurrentForm = new FrmQuery(); break;
                        case 1003: CurrentForm = new FrmStoreProcs(); break;
                        case 1004:
                            {
                                CurrentForm = new FrmMaintenance();
                                // Connect to master Db
                                (CurrentForm as FrmMaintenance).ConnectionString = getMaintenanceConnectString();
                                break;
                            }
                        case 1005: CurrentForm = new FrmSyncData(); break;
                        case 1006: CurrentForm = new FrmSyncTables(); break;
                        case 1007: CurrentForm = new FrmSyncObjText(); break;
                        case 1008: CurrentForm = new FrmGenericQry(); break;
                        case 1009: CurrentForm = new FrmSyncIndexes(); break;   
                        case 1010: CurrentForm = new FrmMtSpNoTable(); break;   
                        case 1101: CurrentForm = new FrmDefaults(); break;
                        default: General.MesDlg("Please selected an item.", 'E'); break;
                    }
                    if (CurrentForm != null)
                    {
                        General.LoadForm(CurrentForm, pnlMain);
                        lblFrmCaption.Text = CurrentForm.Text;
                    }
                }
                else
                    General.MesDlg("Please connect to a server.", 'E');

            } // Form Tag exceed available forms			
        }
        private void changeServer()
        {
            closeCurrentForm();
            this.cbxDBs.Items.Clear();
            btnConnectS.Image = IQ.DbA.Properties.Resources.RedDot;
            btnConnectD.Image = IQ.DbA.Properties.Resources.RedDot;
            if (connectToServer(cbxServer.Text, false))
            {
                btnConnectS.Image = IQ.DbA.Properties.Resources.GreenDot;
                if (String.IsNullOrEmpty(cbxServer.Text))
                    cbxServer.Text = connectDb.Name;
                ServerConnections.Instance.SetServerConnectionStr(connectDb.Server, connectDb.GetConnectionString());
                DataTable datQry = DbHelper.Load_Table(SqlQueries.SqlDataBases);
                for (int i = 0; i < datQry.Rows.Count; i++)
                {
                    this.cbxDBs.Items.Add(datQry.Rows[i][0].ToString());
                }
                cbxDBs.SelectedIndex = cbxDBs.Items.IndexOf(DbHelper.Database);
            }
        }
        private void changeDatabaseConnect()
        {
            btnConnectD.Image = IQ.DbA.Properties.Resources.RedDot;
            Application.DoEvents();
            System.Threading.Thread.Sleep(200);
            if (!String.IsNullOrEmpty(cbxDBs.Text))
            {
                DbHelper.SetConnectionString(get_A_ConnectionString(cbxDBs.Text));
                if (DbHelper.CanConnect)
                    btnConnectD.Image = IQ.DbA.Properties.Resources.GreenDot;
                else
                    General.MesDlg("Could not connect to database: " + cbxDBs.Text, 'E');
            }
        }
        #endregion

        //#region - Public properties / variables - 
        //#endregion

        //#region - Public methods - 
        //#endregion

        //#region - Bind Methods -
        //#endregion

        #region - Form Events -
        // This region is for event handler methods that are called without the user knowing about it.
        // Such as the page loading.
        private void FrmMain_Load(object sender, System.EventArgs e)
        {
            this.WindowState = (FormWindowState)Settings.ReadSettingInt("MainFormState", (int)FormWindowState.Normal);
            if (this.WindowState != FormWindowState.Maximized)
            {
                string[] tlwh = Settings.ReadSettingString("MainForm", "t,l,w,h").Split(',');
                this.Top = tlwh[0].ToIntDefault(10);
                this.Left = tlwh[1].ToIntDefault(10);
                this.Width = tlwh[2].ToIntDefault(Screen.PrimaryScreen.WorkingArea.Width - 20);
                this.Height = tlwh[3].ToIntDefault(Screen.PrimaryScreen.WorkingArea.Height - 20);
            }
            //
            ServerConnections.Instance.LoadServers();
            // Load Server combox
            cbxServer.Items.Clear();
            foreach (DictionaryEntry entry in ServerConnections.Instance.ServerList)
            {
                cbxServer.Items.Add(entry.Key.ToString());
            }
            // Load last settings
            cbxServer.SelectedIndex = cbxServer.Items.IndexOf(Settings.ReadSettingString("LastServer", ""));
            if (cbxServer.SelectedIndex > 0)
                cbxDBs.Text = Settings.ReadSettingString("LastDb", "");
            //
        }
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Settings.SaveSetting("MainFormState", ((int)FormWindowState.Normal).ToString());
            if (Left > 0 && Width > 100)
            {
                Settings.SaveSetting("MainForm", this.Top.ToString() + "," +
                    this.Left.ToString() + "," + this.Width.ToString() + "," + this.Height.ToString());
            }
            Settings.SaveSetting("LastServer", cbxServer.Text);
            Settings.SaveSetting("LastDb", cbxDBs.Text);
        }
        #endregion

        #region - Control Methods -
        // This region is for event handler methods that are called knowingly by the user.
        // Such as a button being clicked.
        private void cbxDBs_SelectedValueChanged(object sender, EventArgs e)
        {
            closeCurrentForm();
            changeDatabaseConnect();
        }
        private void btnConnectS_Click(object sender, System.EventArgs e)
        {
            changeServer();
        }
        private void btnConnectD_Click(object sender, System.EventArgs e)
        {
            changeDatabaseConnect();
        }
        private void tsiMenu_Click(object sender, EventArgs e)
        {
            ToolStripItem tsm = (ToolStripItem)sender;
            load_A_Form(Convert.ToInt32(tsm.Tag));           
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (General.MesDlg("Delete this server from list; " + cbxServer.Text, 'C') == DialogResult.Yes)
            {
                ServerConnections.Instance.RemoveSever(cbxServer.Text);
                cbxServer.Items.Remove(cbxServer.Text);
                if (cbxServer.Items.Count > 0)
                    cbxServer.SelectedIndex = 0;
                else
                {
                    cbxServer.Text = "";
                    cbxServer.SelectedIndex = -1;
                }
            }
        }
        private void tsiExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void lnkWBmail_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("mailto:wicusbotha@live.com?subject=IQ.Db&body=");
        }
        private void tsiExportMD_Click(object sender, EventArgs e)
        {
            if (connectDb.CanConnect)
            {
                if (General.MesDlg("Export meta data for: " + connectDb.Server + ": " + connectDb.Database + "?", 'C')
                    == DialogResult.Yes)
                {
                    SqlMdFileData.SaveMetaData();
                    General.MesDlg("Meta data exported.", 'I');
                    SqlMdFileData.Instance.RefreshFileData();
                }
            }
            else
                General.MesDlg("Please connect to a server.", 'E');
        }
        #endregion
    }
}
